/* This program outputs a file (or stdin) in a caesar cipher.
 *
 * Copyright @ 2020 Joshua Branson <jbranso@dismail.de>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * It is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "encrypt.h"

#define DEFAULT_SHIFT 1

char fileName [128];
short int shift = DEFAULT_SHIFT;

static const struct argp_option options [] =
  {
   {"file" , 'f', "FILE", 0, "Output the caesar cipher of FILE." },
   {"shift", 's', "INT", 0,  "Specify the shift of the cipher." },
   { 0 }
  };

//define an argp parse function
error_t argp_parser (int opt, char *arg, struct argp_state *state)
{
  extern char fileName [];
  extern short int shift;
  switch (opt)
    {
      // if this parser function is called on an option that it doesn't recognize, then don't do anything.
    default:
      return ARGP_ERR_UNKNOWN;
    case 'f':
      {
        memcpy (fileName, arg, strlen (arg));
        break;
      }
    case 's':
      {
        shift = abs ((int) strtol (arg, NULL, 0));
        if (shift >= 26)
          shift = shift % 26;
        break;
      }
    }
  return 0;
}

/* a string containing the basic usage of this program. */
struct argp argp =
  {
   options, argp_parser, 0,
   "A simple program implementing a caesar cipher.\nThe default shift is 1."
  };

int main (int argc, char **argv)
{
  extern short int shift;
  argp_parse (&argp, argc, argv, 0, 0, 0);
  FILE * stream = maybe_open_file ();
  encrypt (shift, stream);
  fclose (stream);
  return 0;
}
